﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using UiUtility;

namespace VFTray
{
	public partial class MainForm : Form
	{
		private string VersionTitle =>
			(" " + System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ExecutablePath).FileVersion
			+ " - " + File.GetLastWriteTime(Application.ExecutablePath));
		internal string OrgTitle = "";

		private SwitchButtonWindows switchBtnWnds = new SwitchButtonWindows();
		internal WndRun wndRun = new WndRun();
		internal WndConfig wndCfgV = new WndConfig();
		internal WndDebug wndDebug = new WndDebug();
		public GradeFileUser.WndUsers wndUsr = new GradeFileUser.WndUsers();


		public MainForm()
		{
			InitializeComponent();
			GlobalParams.MF = this;

			OrgTitle = Text;
			Text = OrgTitle + VersionTitle;
			LogUtility.LOG.Debug(Text);
			
			new ProcessCenter();
#if !NOKEY
			#region processVerify
			_pv.ECheckU += on_PV_CheckU;
			_pv.updateVerifyU(true,GlobalParams.CD.Trayes.Count);

			toolStripStatusLabelVerified.Click += (s, e) => _pv.ShowVerificationDlg();
			#endregion processVerify

			GlobalParams.PC.Status_Verified.Update(true);
#endif
			GlobalParams.PC.Status_Verified.Update(true);
			init_UserLoginout();

			this.Load += (s, e) =>
			{
				ui_timer.Interval = 250;
				ui_timer.Tick += ui_timer_Tick;
				ui_timer.Start();
				
			};
			GlobalParams.PC.Init();
			tableLayoutPanel2.BackColor = Color.LightSlateGray;
			init_toolStripStatusLabelTray();

			wndRun.Init();
			wndCfgV.Init();
			wndUsr.ForeColor = Color.Black;
			wndDebug.Init();

			switchBtnWnds.ButtonSize = new Size(120, 50);
			switchBtnWnds.ShowWindows += (s, e) => { dt_switch_wnd = DateTime.Now; };
			switchBtnWnds.UpdateAuthority += (s, e) =>
			{
				try
				{
					GlobalParams.Auth = GradeFileUser.UserMgr.Instance().User.Authority;
					GradeFileUser.UserMgr.Instance().AddAuth_Name(90, "用户管理");
					labelMode1.Authority = GlobalParams.Auth;

					wndRun.UpdateAuth();
					wndCfgV.UpdateAuth();
					wndDebug.UpdateAuth();
				}
				catch (Exception ex)
				{
					MessageBox.Show(this, ex.Message, "ERROR");
				}
			};

			switchBtnWnds.Add(new Form[] { wndRun, wndCfgV, wndUsr, wndDebug },
			   new string[] { "运行", "配置", "用户管理","调试" },
			   new int[] { 0, 20, 90,100 },
			   tableLayoutPanel1, flowLayoutPanel2);

			switchBtnWnds.UpdateAuth(GlobalParams.Auth);
			switchBtnWnds.ShowWnd(0);

			this.FormClosing += (s, e) =>
			{

				if (MessageBox.Show("确定要退出当前程序吗?", "请确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
				{
					e.Cancel = true;
					return;
				}

				try
				{
					IsClosing.SafeDispose();
					switchBtnWnds.Close();
					if (ui_timer != null) ui_timer.Stop();
					if (GlobalParams.PC != null) GlobalParams.PC.Close();
					System.Diagnostics.Debug.WriteLine("MainForm_FormClosing END");

					System.Threading.Thread.Sleep(100);
				}
				catch (Exception ex)
				{
					LogUtility.LOG.Error("MainForm_FormClosing", ex);
				}

			};
			this.FormClosed += (s, e) =>
			{
				GlobalParams.PC.Closed();
			};
		}
		#region processVerify
		private Mi.ProcessVerify _pv = new Mi.ProcessVerify();
		private void on_PV_CheckU(object sender, Tuple<int, int, string> e)
		{
			switch (e.Item1)
			{
				case -3:
				case -2:
				case -1:
					if (GlobalParams.PC.Status_Verified.LO) return;
					GlobalParams.PC.Status_Verified.Update(false);
					//GlobalParams.PC.processVerificationStop();
					MessageBox.Show(this, e.Item3 + Environment.NewLine + "THE SYSTEM WILL CLOSE NOW! PLEASE CONTACT SERVICES", "UKEY ERROR");
					Close();
					break;
				case 0:
					GlobalParams.PC.Status_Verified.Update(true);
					toolStripStatusLabelVerified.Text = "Verified";
					Text = OrgTitle + VersionTitle;
					break;
				case 1:
					GlobalParams.PC.Status_Verified.Update(false);
					//GlobalParams.PC.processVerificationStop();
					toolStripStatusLabelVerified.Text = "Unverified";
					Text = OrgTitle + VersionTitle + " NO VERIFIED";
					MessageBox.Show("NO VARIFICATION UPDATE CTIME " + e.Item2.ToString());
					break;
				case 2:
					GlobalParams.PC.Status_Verified.Update(false);
					//GlobalParams.PC.processVerificationStop();
					toolStripStatusLabelVerified.Text = "Unverified";
					Text = OrgTitle + VersionTitle + " NO VERIFIED";
					MessageBox.Show("NO VARIFICATION CHECK CTIME");
					break;
				case 3:
					GlobalParams.PC.Status_Verified.Update(false);
					//GlobalParams.PC.processVerificationStop();
					toolStripStatusLabelVerified.Text = "Unverified";
					Text = OrgTitle + VersionTitle + " NO VERIFIED";
					MessageBox.Show("NO VARIFICATION ETIME");
					break;
				case 4:
					GlobalParams.PC.Status_Verified.Update(false);
					//GlobalParams.PC.processVerificationStop();
					toolStripStatusLabelVerified.Text = "Unverified";
					Text = OrgTitle + VersionTitle + " NO VERIFIED";
					MessageBox.Show("NO VARIFICATION DATA" + e.Item2.ToString());
					break;
				case 5:
					GlobalParams.PC.Status_Verified.Update(false);
					//GlobalParams.PC.processVerificationStop();
					toolStripStatusLabelVerified.Text = "Unverified";
					Text = OrgTitle + VersionTitle + " NO VERIFIED";
					MessageBox.Show("NO VALIDATION DATA " + e.Item2.ToString());
					break;
			}
		}
		#endregion processVerify


		#region init_UserLoginout
		private void init_UserLoginout()
		{
			statusLabelUser1.FileName = GlobalParams.CD.UserFile;
			GlobalParams.Auth = GradeFileUser.UserMgr.Instance().User.Authority;
			//GradeFileUserE.UserMgr.Instance().User.Authority = GlobalParams.Auth;
			labelMode1.Authority = GlobalParams.Auth;


			//statusLabelUser1.PreClicked += (s, e) =>
			//{
			//    if (GlobalParams.PC.Status_Start.HI || GlobalParams.PC.IsHoming)
			//    {
			//        MessageBox.Show(this, "请先完成当前操作，再进行用户操作", "Information", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			//        e.Broken = true;
			//        return;
			//    }
			//};

			statusLabelUser1.UserLogout += (s, e) =>
			{
				//e.Name;
				//GlobalParams.MF.Log("登出");
				//Notice(GlobalParams.UM.User.Name + "登出");

				//GlobalParams.PC.PP.SendStop();

				switchBtnWnds.LevelLow = 0;
				switchBtnWnds.LevelHigh = 100;

				if (GradeFileUser.UserMgr.Instance().User.Authority >= switchBtnWnds.GetAuth(switchBtnWnds.Index_Wnd))
					switchBtnWnds.ShowWnd(switchBtnWnds.Index_Wnd);
				else
					switchBtnWnds.ShowWnd(0);

				switchBtnWnds.UpdateAuth(GradeFileUser.UserMgr.Instance().User.Authority);
			};

			statusLabelUser1.UserLogin += (s, e) =>
			{
				if (e.Successed)
				{
					if (e.Authority == 90)
					{
						switchBtnWnds.LevelLow = 90;
						switchBtnWnds.LevelHigh = 90;
					}
					else
					{
						switchBtnWnds.LevelLow = 0;
						switchBtnWnds.LevelHigh = 100;
					}
					dt_switch_wnd = DateTime.Now;

					if (switchBtnWnds.GetAuth(switchBtnWnds.Index_Wnd) <= e.Authority)
						switchBtnWnds.ShowWnd(switchBtnWnds.Index_Wnd);

					switchBtnWnds.UpdateAuth(e.Authority);

					//Notice(dlg.UM.User.Name + " 登入");
					//GlobalParams.MF.Log("登入");
				}
				else
				{
				}
			};
		}
		#endregion init_UserLoginout


		private ThreadSafeDisposable IsClosing = new ThreadSafeDisposable();
		private Timer ui_timer = new Timer();
		private void ui_timer_Tick(object s, EventArgs e)
		{
			if (IsClosing.IsDisposed) return;
			if (!Visible) return;

			if (GlobalParams.PC == null) return;
			_pv.OnTick();
			thisActionTick();

			if (GlobalParams.PC.Status_Verified.HI)
			{
				wndRun.OnUiTimer();
				wndCfgV.OnUiTimer();
				wndDebug.OnUiTimer();
			}

			try
			{
				updateStatusStrip();
			}
			catch (Exception ex)
			{
				LogUtility.LOG.Error("ui_timer_Tick", ex);
			}
		}

		#region action_tick
		DateTime dt_switch_wnd = DateTime.Now;
		private void thisActionTick()
		{
			int auth = GradeFileUser.UserMgr.Instance().User.Authority;
			GlobalParams.Auth = auth;
			try
			{
				if (auth == 100 || auth == 90)
				{
				}
				else if (auth > 10)
				{
					if (GlobalParams.CD.AutoAuthCloseSeconds > 0)//处理
					{
						TimeSpan ts_switch = DateTime.Now - dt_switch_wnd;
						if (ts_switch.TotalSeconds > GlobalParams.CD.AutoAuthCloseSeconds)
						{
							statusLabelUser1.Logout();
						}
					}
					//else 不处理
				}
			}
			catch (Exception ex)
			{
				LogUtility.LOG.Error("thisActionTick", ex);
			}
		}
		#endregion action_tick

		#region status_labeles
		List<ToolStripStatusLabel> list_feeders = new List<ToolStripStatusLabel>();
		List<ToolStripStatusLabel> list_cams = new List<ToolStripStatusLabel>();
		private void init_toolStripStatusLabelTray()
		{
			int i = 0;
			foreach (var f in GlobalParams.CD.Trayes)
			{
				ToolStripStatusLabel tray = new ToolStripStatusLabel();
				tray.Name = "toolStripStatusLabelTray" + i.ToString();
				tray.Size = new System.Drawing.Size(65, 20);
				tray.Text = $"  {f.Name}  ";
				list_feeders.Add(tray);

				var trayAfter = new ToolStripStatusLabel();
				tray.Name = "toolStripStatusLabelTrayAfter" + i.ToString();
				trayAfter.Text = "  ";

				ToolStripStatusLabel cam = new ToolStripStatusLabel();
				cam.Name = "toolStripStatusLabelCam" + i.ToString();
				cam.Size = new System.Drawing.Size(65, 20);
				cam.Text = $"  {f.cfgCamera.Name}  ";
				list_cams.Add(cam);

				var camAfter = new ToolStripStatusLabel();
				cam.Name = "toolStripStatusLabelCamAfter" + i.ToString();
				camAfter.Text = " | ";

				statusStrip1.Items.Insert(i * 4 + 0, tray);
				statusStrip1.Items.Insert(i * 4 + 1, trayAfter);
				statusStrip1.Items.Insert(i * 4 + 2, cam);
				statusStrip1.Items.Insert(i * 4 + 3, camAfter);
				i++;

			}

		}

		private void updateStatusStrip()
		{
			int i = 0;
			foreach (var f in GlobalParams.PC.Feeders)
			{
				FunHelper.UpdateStatusVisibleBackColorGreenYellow(true, GlobalParams.PC.Status_Verified.HI && f.Connected, list_feeders[i]);
				FunHelper.UpdateStatusVisibleBackColorGreenYellow(true, GlobalParams.PC.Status_Verified.HI && f.Cam.Connected, list_cams[i]);
				i++;
			}
		}
		#endregion status_labeles

	}
}
